using Publicuse.Interface;
using Publicuse.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Publicuse.Cache;

using Publicuse.Interface;
using Publicuse.Entity;

namespace Geekeradmin.ExtendsService
{
    public class ClearLoginService : BackgroundService
    {
        private readonly IMySqlSugarService mySqlSugar;

        /// <summary>
        /// 初始化依赖注入
        /// </summary>
        /// <param name="mySqlSugar"></param>
        public ClearLoginService(IMySqlSugarService mySqlSugar)
        {
            this.mySqlSugar = mySqlSugar;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            await base.StartAsync(cancellationToken);
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            await base.StopAsync(cancellationToken);
        }

        public override void Dispose()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                await Task.Delay(6000, stoppingToken); //启动后一分钟执行一次
                InitTask();
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(60000, stoppingToken); //启动后一分钟执行一次
                    InitTask();
                }
            }
            catch (Exception ex)
            {
               
            }
        }

        private void InitTask()
        {
            Task.Factory.StartNew(() => 
            {
                if (DateTime.Now.Hour == 0 && DateTime.Now.Minute < 5)
                {
                    LoginCache.GetLoginCache.GetLoginYzm.Clear();
                    LoginCache.GetLoginCache.GetLoginYzmSuccess.Clear();
                    LoginCache.GetLoginCache.ClearMenu();
                    LoginCache.GetLoginCache.ClearSeesion();

                    var user = TableAtributeUtil.GetTable<User>();
                    var sql = $"update {user} set status=1,retrytime='',loginError=0,retrycount=0 where status=2 and retrycount>=5;";
                    this.mySqlSugar.ExecuteSql(sql, null, out var msg);
                }
            });
        }
    }
}
